
import locationclient from './locationclient.js';
// import Toast from './vant/weapp/toast/toast';
// import Toast from '../../vant/weapp/toast/toast';

var actmodel = {}
actmodel.timestamp = function () {
  var timestamp = new Date().getTime()
  return timestamp;

}
actmodel.getphone = function (encryptedData, iv,code) {
  var app = getApp();
  return new Promise((resolve, reject) => {
    app.util.request({
      'url': 'entry/wxapp/sys_tool',
      showLoading: false,
      method: 'POST',
      data: {
        op: 'getphone',
        encryptedData: encryptedData,
        iv: iv,
        code:code
      },
      success(res) {
        if (res.data.errno == 0) {
          var resultmodel = res.data.data;
          if (resultmodel["status"] == "41009") {
            wx.setStorageSync('userInfo', '');
            app.util.getUserInfo(function (params) {
              wx.showToast({
                title: '请重新授权',
              })

            })
            resultmodel["code"] = "faill";
          }
          else {
            resultmodel["code"] = "success";

          }
          resolve(resultmodel)
        }
        else {
          reject({ code: "faill" })
        }
      },
      fail(res) {
        reject({ code: "faill" })
      }
    })
  })
}

function getUrlParam(url, name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
  var r = url.split('?')[1].match(reg);  //匹配目标参数  
  if (r != null) return unescape(r[2]); return null; //返回参数值  
}


actmodel.distanceByLnglat = function (lng1, lat1, lng2, lat2) {
  var radLat1 = Rad(lat1);
  var radLat2 = Rad(lat2);
  var a = radLat1 - radLat2;
  var b = Rad(lng1) - Rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
  s = Math.round(s * 10000) / 10000;

  var result = {}
  result["val"] = s
  result["unit"] = "m"
  var nval = s
  if (nval > 1000) {
    nval = nval * 0.001
    if (nval < 100) {
      result["formatval"] = nval.toFixed(2)
    }
    else {
      result["formatval"] = nval.toFixed(0)
    }

    result["unit"] = "km"
  }
  else {
    result["formatval"] = Math.round(nval)
  }
  return result
}



function Rad(d) {
  return d * Math.PI / 180.0;
}


/**获取坐标位置 */
actmodel.forcechooseLocation = function (restuserlocation) {
  return new Promise(resolve => {
    wx.getSetting({
      success: (res) => {
     
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          

          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
                resolve({ status: -1, message: '拒绝授权' })
                // return new Promise(resolve=>{

                // })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用的API
                      actmodel.chooseLocation().then(res => {
                        resolve(res)
                      })

                    } else {

                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                      resolve({ status: -1, message: '授权失败' })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
    

          //调用的API      
          actmodel.chooseLocation().then(res => {
            resolve(res)
          })
        } else {   

          actmodel.chooseLocation().then(res => {
            resolve(res)
          })
        }
      }
    })
  })
}
actmodel.chooseLocation = function () {
  return new Promise(resolve => {

    wx.chooseLocation({
      type: 'gcj02',
      success: function (res) {


        if (!res["address"]) {      

          //执行坐标转化
          locationclient.locationaddr({ lat: res["latitude"], lng: res["longitude"] }, null, 0).then(function (tranres) {
          
            resolve({ status: 1, obj: tranres, type: 1 })
          })
        }
        else {     

          var reg = /.+?(省|市|自治区|自治州|县|区)/g;
          res["xcaddr"] = res.address.match(reg)

          resolve({ status: 1, obj: res, type: 2 })
        }





      },
      fail: function (res) {
        resolve({ status: -1, obj: res })
      }
    })
  })
}



/**获取坐标位置 */
actmodel.forcegetLocation = function (cache) {
  return new Promise(resolve => {
    wx.getSetting({
      success: (res) => {
    

        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          console.log("人人人人人人ww")
      
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
                resolve({ status: -1, message: '拒绝授权' })

              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用的API
                      actmodel.getLocation().then(res => {
                        resolve(res)
                      })

                    } else {

                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                      resolve({ status: -1, message: '授权失败' })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
     

          //调用的API      
          actmodel.getLocation(cache).then(res => {
    

    

            resolve(res)
          })
        } else {


          actmodel.getLocation(cache).then(res => {
  

            resolve(res)
          })
        }
      }
    })
  })
}
actmodel.getLocation = function (cache) {
  var app = getApp()
  return new Promise(resolve => {
    if (cache !== false) {
      if (app.globalData.lat) {
        resolve({ status: 1, obj: { latitude: app.globalData.lat, longitude: app.globalData.lng } })
        return;
      }
    }
    // wx.get、Location
    
    wx['get'+'Location']({
      type: 'gcj02',
      success: function (res) {
        app.globalData.lat = res.latitude; //
        app.globalData.lng = res.longitude; //把onload定位时候的经纬度存到全局
        resolve({ status: 1, obj: res })
      },
      fail: function (res) {
        resolve({ status: -1, obj: res })
      }
    })
  })
}

//定位转地址
actmodel.locationotaddr = function (location, rest, get_poi) {

  return new Promise(resolve => {
    locationclient.locationaddr(location, rest, get_poi).then(function (res) {
      resolve(res)
    })
  })

}
actmodel.erpath = function (path) {
  path = path.split('?');   //分割字符串 path[0]等于pages/me/me,path[1]等于scene=table_id%3D8%26shop_id%3D1        
  var scene = path[1];
  var reg = new RegExp("scene=", "g");
  var scene = path.replace(reg, "");
  //手机和开放者工具不一样的地方就在这几步了
  var scene = decodeURIComponent(scene);   //在手机上省略这一步  开发者工具需要   
  scene = scene.split("&");
  var list = {};
  for (var i = 0; i < scene.length; i++) {
    var b = scene[i].split("=");
    list[b[0]] = b[1];
  }
  return { path, para: list };
}
actmodel.uploadFile = function (filepath, vtime) {
 
  wx.showLoading({
    title: '上传中',
  })
  // Toast.loading({
  //   message: '上传中...',
  //   forbidClick: true,
  // });
  var app = getApp()
  var url = app.util.url("entry/wxapp/sys_upload");
  var sessionid = wx.getStorageSync('userInfo').sessionid;
  console.log("sessionid")
  console.log(sessionid)

  url = url + '&op=upimg';
  var state = getUrlParam(url, 'state');
  if (!state && sessionid) {
    url = url + '&state=we7sid-' + sessionid
  }
  url = url + '&state=we7sid-' + sessionid
  var nowPage = getCurrentPages();
  if (nowPage.length) {
    nowPage = nowPage[getCurrentPages().length - 1];
    if (nowPage && nowPage.__route__) {
      url = url + '&m=' + nowPage.__route__.split('/')[0];
    }
  }
  return new Promise(resolve => {
    wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: filepath,
      name: 'file',
      formData: {
        'op': 'upimg'
      },
      success: function (res) {
         console.log(res)

        var reslut = JSON.parse(res.data);
        console.log(reslut)

        if (reslut["errno"] == "41009" && !vtime) {
          wx.setStorageSync('userInfo', '');
          app.util.getUserInfo(function (params) {
            if (!vtime) {
              vtime = 0
            }
            vtime++;
            actmodel.uploadFile(filepath, vtime).then(function (metdata) {
              resolve(metdata)
            })

          })
        }
        else {
          // var reslut = JSON.parse(res.data);
          resolve(reslut)
        }
      },complete:function(){
        wx.hideLoading()
      }
    })
  })

}
module.exports = actmodel;